package com.ms.banner;

import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;

/**
 * 网络加载图片的Task类
 * Created by cdc4512 on 2018/5/7.
 */

class BitmapLoaderTask {

    private Callback callback;
    HttpURLConnection connection = null;
    ImageSource.DecodingOptions decodingOptions = null;
    HashMap<String,PixelMap> tempPixeMap = null;

    public BitmapLoaderTask(String url, Callback callback) {
        this.callback = callback;
        getImg(url);
    }

    private void getImg(String urlImage) {

        if(tempPixeMap == null){
            tempPixeMap = new HashMap<>();
        }
        PixelMap tmp = tempPixeMap.get(urlImage);
        if(tmp == null) {

            if (decodingOptions == null) {
                decodingOptions = new ImageSource.DecodingOptions();
                decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
            }
            try {
                URL url = new URL(urlImage);
                URLConnection urlConnection = url.openConnection();
                if (urlConnection instanceof HttpURLConnection) {
                    connection = (HttpURLConnection) urlConnection;
                }
                if (connection != null) {
                    connection.connect();
                    // 之后可进行url的其他操作
                    // 得到服务器返回过来的流对象
                    InputStream inputStream = urlConnection.getInputStream();
                    ImageSource imageSource = ImageSource.create(inputStream, new ImageSource.SourceOptions());

                    // 普通解码叠加旋转、缩放、裁剪
                    PixelMap pixelMap = imageSource.createPixelmap(decodingOptions);
                    callback.result(pixelMap);
                    tempPixeMap.put(urlImage,pixelMap);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            callback.result(tmp);
        }
    }

    interface Callback {
        void result(PixelMap bitmap);
    }
}
